<template>
  <!-- <div :style="cssVars" class="image-loader-container"> css使用js变量-->
  <div class="image-loader-container">
    <img
      v-if="!everythingDone"
      class="small-img"
      :src="placeholder"
      alt=""
    />
    <img
      :style="{ opacity: originOpacity, transition: `${duration / 1000}s` }"
      class="big-img"
      :src="src"
      @load="loaded"
      alt=""
    />
  </div>
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      required: true,
    },
    placeholder: {
      type: String,
      required: true,
    },
    duration: {
      type: Number,
      required: false,
      default: 500,
    },
  },
  data() {
    return {
      originLoaded: false, // 原图是否加载完成
      everythingDone: false, // 全部行为是否完成
    };
  },
  computed: {
    cssVars() {
      return {
        "--duration": this.duration / 1000 + "s",
      };
    },
    originOpacity() {
      return this.originLoaded ? 1 : 0;
    },
  },
  methods: {
    loaded() {
      // document.querySelector(".big-img").style.opacity = 1; // 这样写不合适, vue中应该从状态考虑
      this.originLoaded = true;
      setTimeout(() => {
        this.everythingDone = true; // 这里必须用箭头函数, 否则this指向会出问题
        this.$emit("load");
      }, this.duration);
    },
  },
};
</script>

<style lang="less" scoped>
@import "~@/styles/mixin";
.image-loader-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  img {
    .self-fill();
  }
  .small-img {
    filter: 1.2vw;
  }
  .big-img {
    z-index: 10;
    // opacity: 0;
    // transition: all var(--duration); // css使用js变量的方法
  }
}
</style>
